package com.fashiontextile.common.utils;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.fashiontextile.common.config.properties.AliyunOssProperties;
import com.fashiontextile.common.entity.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;

@Slf4j
@Service
@EnableConfigurationProperties(AliyunOssProperties.class)
public class AliyunOSSUtils {
    private final AliyunOssProperties properties;
    private final OSS ossClient;

    public AliyunOSSUtils(AliyunOssProperties properties) {
        this.properties = properties;
        this.ossClient = new OSSClientBuilder().build(
                properties.getEndPoint(),
                properties.getAccessKey(),
                properties.getAccessSecret()
        );
    }

    /**
     * 上传文件，以IO流方式
     *
     * @param inputStream 输入流
     * @param objectName  唯一objectName（在oss中的文件名字）
     */
    public R<?> uploadStream(InputStream inputStream, String objectName) {
        try {
            ossClient.putObject(properties.getBucketName(), properties.getNamespace() + objectName, inputStream);
            return R.success(properties.getUrlPrefix() + properties.getNamespace() + objectName, "上传成功");
        } catch (Exception e) {
            log.error("OSS文件上传失败", e);
            throw e;
        }
    }

    /**
     * 上传文件，以MuiltPart方式
     *
     * @param file 文件
     * @param objectName  唯一objectName（在oss中的文件名字）
     */
    public R<?> uploadMultipart(MultipartFile file, String objectName) throws Exception {
        return uploadStream(file.getInputStream(), objectName);
    }

    /**
     * 删除OSS中的单个文件
     *
     * @param objectName 唯一objectName（在oss中的文件名字）
     */
    public boolean delete(String objectName) {
        try {
            ossClient.deleteObject(properties.getBucketName(), properties.getNamespace() + objectName);
            return true;
        } catch (Exception e) {
            log.error("OSS文件删除失败", e);
            return false;
        }
    }
}
